package com.kaguya.vams.security.filter;

import com.kaguya.vams.common.constant.Constants;
import com.kaguya.vams.common.exception.CaptchaException;
import com.kaguya.vams.security.handler.LoginFailureHandler;
import com.kaguya.vams.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码 过滤器 在登录过滤器前
 *
 * @author : kaguya
 * @date : 23:57 2021/7/29
 */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    private final String loginUrl = "/login";
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    LoginFailureHandler loginFailureHandler; //登录失败处理器

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String url = request.getRequestURI();
        if (loginUrl.equals(url) && request.getMethod().equals("POST")) {
            log.info("获取到login链接，正在校验验证码 -- " + url);
            try {
                validate(request);
            } catch (CaptchaException e) {
                log.info(e.getMessage());
                // 交给登录失败处理器处理
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String token = request.getParameter("imgKey");
        if (StringUtils.isBlank(code) || StringUtils.isBlank(token)) {
            throw new CaptchaException("验证码不能为空");
        } else {


            if (!code.equals(redisUtils.getCacheObject(token))) {

                // 一次性使用
                redisUtils.deleteObject(token);

                throw new CaptchaException("验证码不正确");
            }
        }

    }

}
